﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;

namespace LongSpeed.WebSite.Behaviors
{
    public class ServerConfig
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// Cpu
        /// </summary>
        public string CPU { get; set; }
        /// <summary>
        /// 内存
        /// </summary>
        public string RAM { get; set; }
        /// <summary>
        /// 硬盘
        /// </summary>
        public string HD { get; set; }
        /// <summary>
        /// 接入宽带
        /// </summary>
        public string Broadband { get; set; }
        /// <summary>
        /// 月流量
        /// </summary>
        public string MonthlyFlow { get; set; }
        /// <summary>
        /// 单价
        /// </summary>
        public string UnitPrice { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Memo { get; set; }

        /// <summary>
        /// 是否推荐服务器
        /// </summary>
        public bool IsRecommend { get; set; }

        /// <summary>
        /// 是否特价服务器
        /// </summary>
        public bool IsSpecials { get; set; }

        private string _LastModifyDate;
        /// <summary>
        /// 添加时间
        /// </summary>
        public string LastModifyDate
        {
            get
            {
                if (string.IsNullOrEmpty(_LastModifyDate))
                {
                    _LastModifyDate = DateTime.Now.ToString("yyyy-HH-dd hh:mm:ss");
                }
                return _LastModifyDate;
            }
            private set { _LastModifyDate = value; }
        }
        /// <summary>
        /// 促销价
        /// </summary>
        public string PromotionalPrice { get; set; }
        /// <summary>
        /// 菜单Id
        /// </summary>
        int mid = 0;
        public int MemuId
        {
            get
            {
                if (this._ParentMemu != null)
                {
                    mid = this._ParentMemu.ID;
                }
                return mid;
            }
            set { mid = value; }
        }
        /// <summary>
        /// Ip数（范围）
        /// </summary>
        public string IpRange { get; set; }
        /// <summary>
        /// 排序索引
        /// </summary>
        public int SortIndex { get; set; }

        Memu _ParentMemu;

        /// <summary>
        /// 所属菜单
        /// </summary>
        public Memu ParentMemu
        {
            get
            {
                if (_ParentMemu == null)
                {
                    _ParentMemu = new Memu();
                    _ParentMemu.Init(this.MemuId);
                }
                return _ParentMemu;
            }

            set { _ParentMemu = value; }
        }


        public IList<ServerConfig> GetServersByParent(Memu parentMenu)
        {
            IList<ServerConfig> servers = new List<ServerConfig>();
            string where = string.Format(" MemuId = {0}", parentMenu.ID);
            var ds = GetData(where);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    ServerConfig m = RowToEntity(parentMenu, row);
                    servers.Add(m);
                }
            }
            return servers;
        }
        /// <summary>
        /// 根据菜单Id分页获取服务器配置列表
        /// </summary>
        /// <param name="parentMemu">所属菜单</param>
        /// <param name="pageIndex">当前第几页（从第一页开始）</param>
        /// <param name="pageCount">每页显示数量</param>
        /// <param name="sumPageCount">总共页数</param>
        /// <returns></returns>
        public IList<ServerConfig> GetServersByParentOfPage(Memu parentMemu, int pageIndex, int pageCount, ref int sumPageCount)
        {
            IList<ServerConfig> servers = new List<ServerConfig>();

            string cmdone = string.Format("select top {0} * from ( select * from T_ServerConfig where MemuId = @MemuId order by SortIndex asc )", pageCount);
            string cmdStr = string.Format("select top {0} * from ( select * from T_ServerConfig where MemuId = @MemuId and ID not in (select top {1} * from ( select ID from  T_ServerConfig where MemuId = @MemuId  order by SortIndex asc ) ) order by SortIndex asc )", pageCount, (pageIndex - 1) * pageCount);
            var par = new System.Data.OleDb.OleDbParameter("@MemuId", System.Data.OleDb.OleDbType.Integer) { Value = parentMemu.ID };

            DataSet ds = null;
            if (pageIndex == 1)
            {
                ds = OleDbHelper.Query(cmdone, par);
            }
            else if (pageIndex > 1)
            {
                ds = OleDbHelper.Query(cmdStr, par);
            }

            object sumCount = OleDbHelper.Query("select count(*) from T_ServerConfig where MemuId = @MemuId ", par).Tables[0].Rows[0][0];
            sumPageCount = sumCount != null ? Convert.ToInt32(sumCount) % pageCount == 0 ? Convert.ToInt32(sumCount) / pageCount : Convert.ToInt32(sumCount) / pageCount + 1 : 0;

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    ServerConfig m = RowToEntity(parentMemu, row);
                    servers.Add(m);
                }
            }
            return servers;
        }

        private static ServerConfig RowToEntity(Memu parentMenu, DataRow row)
        {
            ServerConfig m = new ServerConfig()
            {
                ID = Convert.ToInt32(row["ID"]),
                Memo = row["Memo"] + "",
                Name = row["S_Name"] + "",
                MemuId = parentMenu.ID,
                SortIndex = Convert.ToInt32(row["SortIndex"]),
                Broadband = row["Broadband"] + "",
                CPU = row["CPU"] + "",
                HD = row["HD"] + "",
                IpRange = row["IpRange"] + "",
                MonthlyFlow = row["MonthlyFlow"] + "",
                ParentMemu = parentMenu,
                RAM = row["RAM"] + "",
                UnitPrice = row["UnitPrice"] + "",
                PromotionalPrice = row["PromotionalPrice"] + "",
                IsRecommend = Convert.ToBoolean(row["IsRecommend"]),
                IsSpecials = Convert.ToBoolean(row["IsSpecials"]),
                LastModifyDate = Convert.ToDateTime(row["LastModifyDate"]).ToString("yyyy-HH-dd hh:mm:ss"),
            };
            return m;
        }
        /// <summary>
        /// 获取特价服务器
        /// </summary>
        ///<param name="partMId">
        /// 上级菜单Id（一级）
        /// <para>1、如果Id=0 则取所有的特价服务器</para>
        /// <para>2、否则就取该菜单下的特价服务器</para>
        /// </param>
        /// <returns></returns>
        public IList<ServerConfig> GetSpecialsServers(int partMId)
        {
            IList<ServerConfig> servers = new List<ServerConfig>();
            string where = string.Format(" IsSpecials = true");

            if (partMId != 0)
            {
                var str = " select ID from t_menus where parentid = " + partMId;

                where += string.Format(" AND MemuId in (" + str + ")");
            }

            var ds = OleDbHelper.Query(" SELECT top 10 *  FROM  T_ServerConfig where " + where);


            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    int memuid = Convert.ToInt32(row["MemuId"]);
                    var parMemu = new Memu();
                    parMemu.Init(memuid);
                    ServerConfig m = RowToEntity(parMemu, row);
                    servers.Add(m);
                }
            }
            return servers;
        }
        /// <summary>
        /// 获取推荐服务
        /// </summary>
        /// <returns></returns>
        public IList<ServerConfig> GetRecommendServers()
        {
            IList<ServerConfig> servers = new List<ServerConfig>();
            string where = string.Format(" IsRecommend = true");
            var ds = OleDbHelper.Query(" SELECT top 10 *  FROM  T_ServerConfig where " + where);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    int memuid = Convert.ToInt32(row["MemuId"]);
                    var parMemu = new Memu();
                    parMemu.Init(memuid);
                    ServerConfig m = RowToEntity(parMemu, row);
                    servers.Add(m);
                }
            }
            return servers;
        }

        public DataSet GetData(string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" SELECT  *  FROM  T_ServerConfig ");
            if (!string.IsNullOrEmpty(where))
            {
                strSql.Append(" where  " + where);
            }
            strSql.Append(" ORDER BY SortIndex ");
            return OleDbHelper.Query(strSql.ToString());
        }

        public void Init(int sid)
        {
            string where = string.Format(" ID = {0} ", sid);
            var ds = GetData(where);


            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    int memuid = Convert.ToInt32(row["MemuId"]);
                    var parMemu = new Memu();
                    parMemu.Init(memuid);
                    ServerConfig m = RowToEntity(parMemu, row);
                    this.Broadband = m.Broadband;
                    this.CPU = m.CPU;
                    this.HD = m.HD;
                    this.ID = m.ID;
                    this.IpRange = m.IpRange;
                    this.IsRecommend = m.IsRecommend;
                    this.IsSpecials = m.IsSpecials;
                    this.LastModifyDate = m.LastModifyDate;
                    this.Memo = m.Memo;
                    this.MemuId = m.MemuId;
                    this.MonthlyFlow = m.MonthlyFlow;
                    this.Name = m.Name;
                    this.ParentMemu = parMemu;
                    this.PromotionalPrice = m.PromotionalPrice;
                    this.RAM = m.RAM;
                    this.SortIndex = m.SortIndex;
                    this.UnitPrice = m.UnitPrice;

                    break;
                }
            }

        }

        public bool Save()
        {
            object name, cpu, ram, hd, bb, mf, up, pm, ir, memo;
            if (this.Name == null) name = DBNull.Value; else name = this.Name;
            if (this.CPU == null) cpu = DBNull.Value; else cpu = this.CPU;
            if (this.RAM == null) ram = DBNull.Value; else ram = this.RAM;
            if (this.HD == null) hd = DBNull.Value; else hd = this.HD;
            if (this.Broadband == null) bb = DBNull.Value; else bb = this.Broadband;
            if (this.MonthlyFlow == null) mf = DBNull.Value; else mf = this.MonthlyFlow;
            if (this.UnitPrice == null) up = DBNull.Value; else up = this.UnitPrice;
            if (this.ParentMemu == null) pm = DBNull.Value; else pm = this.ParentMemu;
            if (this.IpRange == null) ir = DBNull.Value; else ir = this.IpRange;
            if (this.Memo == null) memo = DBNull.Value; else memo = this.Memo;

            string execSql = "";
            if (this.ID == 0)
            {
                execSql = " insert into    T_ServerConfig ( S_Name, CPU, RAM, HD, Broadband, MonthlyFlow, UnitPrice, MemuId, IpRange,  [Memo], IsSpecials,IsRecommend,PromotionalPrice) values ( @S_Name, @CPU, @RAM, @HD, @Broadband, @MonthlyFlow, @UnitPrice, @MemuId, @IpRange, @Memo, @IsSpecials,@IsRecommend,@PromotionalPrice) ";
                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {
                 new System.Data.OleDb.OleDbParameter("@S_Name",name),
                 new System.Data.OleDb.OleDbParameter("@CPU",cpu),
                 new System.Data.OleDb.OleDbParameter("@RAM",ram),
                 new System.Data.OleDb.OleDbParameter("@HD", hd),
                 new System.Data.OleDb.OleDbParameter("@Broadband",bb),
                 new System.Data.OleDb.OleDbParameter("@MonthlyFlow",mf),    
                 new System.Data.OleDb.OleDbParameter("@UnitPrice",up),
                 new System.Data.OleDb.OleDbParameter("@MemuId",this.ParentMemu.ID),
                 new System.Data.OleDb.OleDbParameter("@IpRange",ir),
                 new System.Data.OleDb.OleDbParameter("@Memo",memo),
                 new System.Data.OleDb.OleDbParameter("@IsSpecials",this.IsSpecials),
                 new System.Data.OleDb.OleDbParameter("@IsRecommend",this.IsRecommend),
                 new System.Data.OleDb.OleDbParameter("@PromotionalPrice",this.PromotionalPrice),
                };

                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    this.ID = OleDbHelper.GetMaxID("ID", " T_ServerConfig");

                    return true;
                }
            }
            else
            {
                execSql = "update   T_ServerConfig set  S_Name=@Name, CPU=@CPU, RAM=@RAM, HD=@HD, Broadband=@Broadband , MonthlyFlow=@MonthlyFlow, UnitPrice=@UnitPrice, IpRange=@IpRange,  [Memo]=@Memo,IsSpecials=@IsSpecials,IsRecommend=@IsRecommend,LastModifyDate=Now(),PromotionalPrice=@PromotionalPrice ,SortIndex=@SortIndex where ID = @ID";
                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {
                new System.Data.OleDb.OleDbParameter("@S_Name",name),
                 new System.Data.OleDb.OleDbParameter("@CPU",cpu),
                 new System.Data.OleDb.OleDbParameter("@RAM",ram),
                 new System.Data.OleDb.OleDbParameter("@HD", hd),
                 new System.Data.OleDb.OleDbParameter("@Broadband",bb),
                 new System.Data.OleDb.OleDbParameter("@MonthlyFlow",mf),    
                 new System.Data.OleDb.OleDbParameter("@UnitPrice",up),
                 new System.Data.OleDb.OleDbParameter("@IpRange",ir),
                 new System.Data.OleDb.OleDbParameter("@Memo",memo),          
                 new System.Data.OleDb.OleDbParameter("@IsSpecials",this.IsSpecials),
                 new System.Data.OleDb.OleDbParameter("@IsRecommend",this.IsRecommend),  
                 new System.Data.OleDb.OleDbParameter("@PromotionalPrice",this.PromotionalPrice),
                 new System.Data.OleDb.OleDbParameter("@SortIndex",this.SortIndex),
                 new System.Data.OleDb.OleDbParameter("@ID",this.ID),
                };

                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    return true;
                }
            }

            return false;
        }
        public bool Delete()
        {
            string execSql = "";
            execSql = "delete from  T_ServerConfig where  ID = @ID ";
            System.Data.OleDb.OleDbParameter par = new System.Data.OleDb.OleDbParameter("@ID", this.ID);

            if (OleDbHelper.ExecuteSql(execSql, par) > 0)
            {
                return true;
            }

            return false;
        }

    }
}